﻿using MyInspiration.Models;
using QConnectSDK;
using QConnectSDK.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using System.Configuration;
using NetDimension.OpenAuth.Sina;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MyInspiration.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        MyIdeaEntities idea = new MyIdeaEntities();
        public ActionResult Index(int id = 1)
        {
            List<IdeaList> myList = idea.IdeaList.Where(m => m.idea_IsPrivate == false).ToList();
            return View(myList.OrderByDescending(m => m.idea_Create_Time).ToPagedList<IdeaList>(id, 8));
        }
        /// <summary>
        /// 添加灵感窗口
        /// </summary>
        /// <returns></returns>
        public ActionResult Add_Inspiration()
        {
            return PartialView();
        }
        /// <summary>
        /// 添加灵感
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        [ValidateAntiForgeryTokenOnAllPosts]
        public ActionResult Add(IdeaList i)
        {
            
            if (!Request.IsAjaxRequest()) return Content("<script>while(true)console.log(1);</script>");
            if (string.IsNullOrEmpty(i.idea_Publisher) || i.idea_Publisher.Trim() == "")
            {
                i.idea_Publisher = "匿名";
            }
            i.idea_IsPrivate = false;//是否私密
            i.idea_Status = 1;//0：为草稿 1：发布 (暂如此设计)
            i.idea_Create_Time = DateTime.Now;
            idea.IdeaList.Add(i);
            idea.SaveChanges();

            var jsonObj = new { res = "Success", info = "成功" };
            return Json(jsonObj, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 删除灵感窗口
        /// </summary>
        /// <returns></returns>
        public ActionResult Delete_Inspiration()
        {
            return PartialView();
        }
        /// <summary>
        /// 删除灵感
        /// </summary>
        /// <returns></returns>
        public ActionResult Delete(IdeaList i)
        {
            var jsonObj = new { res = "Success", info = "成功" };
            if (i.idea_opPwd != "231080880")
            {
                jsonObj = new { res = "fail", info = "失败" };
            }
            else
            {
                IdeaList temp = idea.IdeaList.FirstOrDefault(c => c.idea_Id == i.idea_Id);
                if (temp != null)
                {
                    idea.IdeaList.Remove(temp);
                    idea.SaveChanges();
                }
            }
            return Json(jsonObj, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// QQ登录
        /// </summary>
        /// <returns>跳转URL</returns>
        public ActionResult QzoneLogin()
        {
            var context = new QzoneContext();
            string state = Guid.NewGuid().ToString().Replace("-", "");
            string scope = "get_user_info";
            var authenticationUrl = context.GetAuthorizationUrl(state, scope);
            Session["state"] = state;
            return new RedirectResult(authenticationUrl);
        }
        /// <summary>
        /// QQ回调地址
        /// </summary>
        /// <param name="code">登录验证CODE</param>
        /// <returns>返回主页</returns>
        public ActionResult QzoneCallback(String code)
        {

            if (!string.IsNullOrEmpty(code))
            {
                QOpenClient qzone = null;
                QConnectSDK.Models.User currentUser = null;
                string state = Session["state"].ToString();
                try
                {
                    qzone = new QOpenClient(code, state);
                }
                catch (Exception ex)
                {

                    throw;
                }
                currentUser = qzone.GetCurrentUser();

                string nickName = currentUser.Nickname;
                string openId = qzone.OAuthToken.OpenId;
                string accessToken = qzone.OAuthToken.AccessToken;

                Session["uid"] = openId;
                Session["nickName"] = nickName;
                Session["Figureurl"] = currentUser.Figureurl.Substring(0, currentUser.Figureurl.LastIndexOf('/') + 1) + "50";

                return RedirectToAction("Index", "Personal");
            }
            return Content("<script>location='/home/index';alert('登录失败!');</script>");
        }

        /// <summary>
        /// 微博登录
        /// </summary>
        /// <returns>跳转URL</returns>
        public ActionResult WeiboLogin()
        {
            var settings = ConfigurationManager.AppSettings;
            var authenticationUrl = settings["authorizeUrl"] + "?client_id=" + settings["appKey"] + "&response_type=code&redirect_uri=" + settings["callbackUrl"];
            return new RedirectResult(authenticationUrl);
        }
        /// <summary>
        /// 微博回调地址
        /// </summary>
        /// <param name="code">登录验证CODE</param>
        /// <returns>返回主页</returns>
        public ActionResult WeiboCallback(string code)
        {
            if (!string.IsNullOrEmpty(code))
            {
                var client = GetOpenAuthClient();

                client.GetAccessTokenByCode(code);

                if (client.IsAuthorized)
                {
                    //用session记录access token
                    Session["access_token"] = client.AccessToken;
                    //用cookie记录uid
                    Response.AppendCookie(new HttpCookie("uid", client.UID) { Expires = DateTime.Now.AddDays(7) });
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 封装一个方法来初始化OpenAuth客户端
        /// </summary>
        /// <returns></returns>
        private SinaWeiboClient GetOpenAuthClient()
        {
            var accessToken = Session["access_token"] == null ? string.Empty : (string)Session["access_token"];
            var uid = Request.Cookies["uid"] == null ? string.Empty : Request.Cookies["uid"].Value;

            var settings = ConfigurationManager.AppSettings;
            var client = new SinaWeiboClient(settings["appKey"], settings["appSecret"], settings["callbackUrl"], accessToken, uid);

            return client;
        }
    }
}
